/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.apache.wikimark.http;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.URISyntaxException;
import java.net.URL;

import javax.servlet.Servlet;

import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.ContextHandler;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;

import org.apache.wikimark.ScriptServletProvider;

/**
 * Localhost loopback servlet container for serving local files
 * 
 * @author Sergey I. Salishev
 */
public class LocalConnectivity extends HttpConnectivity {
	
	private final ScriptServletProvider servletProvider;
	private Server server;

	/**
	 * @param servletClass the class of the servlet request processor
	 */
	public LocalConnectivity(Class<? extends Servlet> servletClass) {
		servletProvider = new ScriptServletProvider(servletClass);
	}

	public void setBaseURL(final URL url) {
		File file;
		try {
			file = new File(url.toURI());
		} catch (URISyntaxException e) {
			throw new RuntimeException(e);
		}

		final int port = getFreePort();
		final String path = file.getParentFile().getAbsolutePath();

		createServer(file, port, path);
				
		URL newURL;
		try {
			newURL = new URL("http", "localhost", port, "/" + file.getName());
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		super.setBaseURL(newURL);
	}

	private void createServer(File file, final int port, final String path) {
		server = new Server(port);    
		Context root = new Context(server,"/",Context.SESSIONS);
		ContextHandler alias = new ContextHandler("/");
		alias.setResourceBase(path);
		root.addHandler(alias);
		root.addServlet(new ServletHolder(servletProvider.createServlet(file)), 
				"/" + file.getName() + "/*");
		
		try {
			server.start();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	private static int getFreePort() {
		ServerSocket s;
		try {
			s = new ServerSocket(8080);
		} catch (IOException e) {
			try {
				s = new ServerSocket(0);
			} catch (IOException e1) {
				throw new RuntimeException(e1);
			}
		}
		int port = s.getLocalPort();
		try {
			s.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return port;
	}
	
	protected void finalize() throws Throwable {
		close();
		super.finalize();
	}
	
	public void close() throws IOException {
		try {
			server.stop();
		} catch (Exception e) {
			e.printStackTrace();
			throw new IOException(e.getMessage());
		}
	}
}
